package com.tenglong.teacher.ui.homepage;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.SeClass;
import com.tenglong.teacher.ui.utils.MyUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class HomepageClassAdatper extends BaseAdapter {
    private LayoutInflater inflater;
    private List<SeClass> mData;
    private LruCache<String, BitmapDrawable> mImageCache;
    private ListView listview;
    private Context mContext;

    public HomepageClassAdatper(Context context, List<SeClass> Data) {
        inflater = LayoutInflater.from(context);
        this.mContext = context;
        this.mData = Data;
        int maxCache = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxCache / 8;
        mImageCache = new LruCache<String, BitmapDrawable>(cacheSize) {
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }
        };
    }

    // 要绑定的条目的数目
    @Override
    public int getCount() {
        return mData.size();
    }

    // 根据一个索引（位置）获得该位置的对象
    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    // 获取条目的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 获取该条目要显示的界面
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (listview == null) {
            listview = (ListView) parent;
        }
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_class, parent, false);

            holder = new ViewHolder();
            holder.tv_className = convertView.findViewById(R.id.tv_className);
            holder.iv_header = convertView.findViewById(R.id.iv_header);
            holder.tv_teacher_name = convertView.findViewById(R.id.tv_teacher_name);
            holder.tv_stu_num = convertView.findViewById(R.id.tv_stu_num);
            holder.classCode = convertView.findViewById(R.id.classCode);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        SeClass bean = mData.get(position);

        if (bean.isInClass()) {
            String name = bean.getName();
            if (name == null) {
                name = "";
            }
            SpannableStringBuilder builder = new SpannableStringBuilder(name + "（" + "上课中" + "）");
            builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.app_red)), name.length(), name.length() + 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.tv_className.setText(builder);
        } else {
            holder.tv_className.setText(bean.getName());
        }
        holder.classCode.setVisibility(TextUtils.isEmpty(bean.getClassno()) ? View.GONE : View.VISIBLE);
        if (holder.classCode.getVisibility() == View.VISIBLE) {
            holder.classCode.setText("班级ID：" + bean.getClassno());
        }
        holder.iv_header.setTag(bean.getDirectorAvatar());
        holder.tv_teacher_name.setText(bean.getDirectorName().equals("") ? "暂无" : bean.getDirectorName());
        holder.tv_stu_num.setText(bean.getStudentCount() + "人");
        if (bean.getDirectorName() != null) {
            int len = bean.getDirectorName().length();
            if (len > 2) {
                holder.iv_header.setText(bean.getDirectorName().substring(len - 2, len));
            } else {
                if (len == 0) {
                    holder.iv_header.setText("暂无");
                } else {
                    holder.iv_header.setText(bean.getDirectorName());
                }
            }
        } else {
            holder.iv_header.setText("暂无");
        }

        return convertView;
    }

    // 新建holder类，对listview进行简单优化
    private class ViewHolder {
        TextView tv_className;
        TextView iv_header;
        TextView tv_teacher_name;
        TextView tv_stu_num;
        TextView classCode;
    }

    class ImageTask extends AsyncTask<String, Void, BitmapDrawable> {

        private String imageUrl;

        @Override
        protected BitmapDrawable doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadImage();
            BitmapDrawable db = new BitmapDrawable(listview.getResources(),
                    bitmap);
            // 如果本地还没缓存该图片，就缓存
            if (mImageCache.get(imageUrl) == null) {
                mImageCache.put(imageUrl, db);
            }
            return db;
        }

        @Override
        protected void onPostExecute(BitmapDrawable result) {
            // 通过Tag找到我们需要的ImageView，如果该ImageView所在的item已被移出页面，就会直接返回null
            ImageView iv = listview.findViewWithTag(imageUrl);
            if (iv != null && result != null) {
                iv.setImageDrawable(result);
            }
        }

        /**
         * 根据url从网络上下载图片
         *
         * @return
         */
        private Bitmap downloadImage() {
            HttpURLConnection con = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }

            return bitmap;
        }

    }
}
